package nciae.db.controller;

import nciae.db.pojo.entity.Settings;
import nciae.db.service.SettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/system/settings")
public class SettingsController {

    @Autowired
    private SettingsService settingsService;


    // 加载系统设置页面
    @GetMapping
    public String settingsPage() {
        System.out.println("Accessing settings page...");
        return "settings/index"; // 对应 Thymeleaf 模板 src/main/resources/templates/settings/index.html
    }

    // 获取系统设置（AJAX）
    @ResponseBody
    @GetMapping("/data")
    public Settings getSettings() {
        Settings settings = settingsService.getSettings();
        if (settings == null) {
            throw new RuntimeException("未找到初始设置数据");
        }
        return settings;
        //return settingsService.getSettings();
    }

    // 更新系统设置（AJAX）
    @ResponseBody
    @PostMapping("/save")
    public String saveSettings(@RequestBody Settings settings) {
        float attendanceRate = settings.getAttendanceRate();
        float homeworkRate = settings.getHomeworkRate();
        float logRate = settings.getLogRate();
        if(attendanceRate + homeworkRate + logRate != 100){
            return "设置保存失败，请检查数据总和是否为100！";
        }

        boolean success = settingsService.updateSettings(settings);
        return success ? "设置保存成功！" : "保存失败，请重试！";
    }
}
